<template>
  <div>
    <div class="list-box">
      <el-collapse v-model="activeName">
        <el-collapse-item
          v-for="(item, index) in list"
          :name="index"
          :key="index"
        >
          <div
            slot="title"
            class="flex"
            style="justify-content: space-between; width: 100%"
          >
            <div class="cu-title" @click.stop>
              <el-radio-group
                style="margin-right: 20px"
                v-model="item.type"
                class="ml-4"
              >
                <el-radio label="device" size="large">设备监听</el-radio>
              </el-radio-group>
              <div class="item">
                <select-product
                  :indexes="index"
                  :pk="item.pk"
                  @onSelect="handleSelectProduct"
                  ref="refproduct"
                ></select-product>
              </div>
              <div class="item" v-if="item.pk">
                <select-device
                  :indexes="index"
                  placeholder="默认全部设备"
                  :pk="item.pk"
                  :dn="item.dn"
                  @handleEmits="handleEmits"
                ></select-device>
              </div>
            </div>
            <div style="padding-right: 10px">
              <el-button size="small" @click="removeListener(index)"
                >删除</el-button
              >
            </div>
          </div>
          <div class="condition-box" v-if="item.pk">
            <div class="main">
              <div class="title">条件</div>
              <div class="main-box">
                <div
                  class="box"
                  v-for="(cond, condIndex) in item.conditions"
                  :key="condIndex"
                >
                  <div class="item">
                    <el-row style="width: 100%">
                      <el-col :span="7">
                        <el-select
                          v-model="cond.identifier"
                          placeholder="请选择"
                          size="small"
                          @change="
                            (e) => conditionChange(cond, index, e, condIndex)
                          "
                        >
                          <el-option-group
                            v-for="group in options"
                            :key="group.name"
                            :label="group.name"
                          >
                            <el-option
                              v-for="item in group.items"
                              :key="item.identifier"
                              :label="item.name"
                              :value="item.identifier"
                            >
                            </el-option>
                          </el-option-group>
                        </el-select>
                      </el-col>
                      <el-col
                        :span="15"
                        v-show="!cond?.identifier?.endsWith(':*')"
                      >
                        <el-row
                          class="param-item"
                          v-for="(param, paramIndex) in cond.parameters"
                          :key="param.identifier"
                        >
                          <!-- 只有属性上报才显示+ v-if="cond.identifier == 'report'"-->
                          <el-col :span="10" v-if="cond.identifier == 'report'">
                            <el-select
                              v-model="param.identifier"
                              style="width: 100%"
                              size="small"
                              @change="setlisteners"
                            >
                              <el-option
                                v-for="p in properties"
                                :label="p.name"
                                :value="p.identifier"
                                :key="p.identifier"
                              />
                            </el-select>
                          </el-col>
                          <!-- 事件 -->
                          <el-col :span="10" v-else>
                            <el-select
                              v-model="param.identifier"
                              style="width: 100%"
                              size="small"
                              @change="onOutputData"
                            >
                              <el-option
                                v-for="p in outputData"
                                :label="p.name"
                                :value="p.identifier"
                                :key="p.identifier"
                              />
                            </el-select>
                          </el-col>
                          <el-col :span="6">
                            <el-select
                              v-model="param.comparator"
                              size="small"
                              @change="setlisteners"
                            >
                              <el-option
                                v-for="cp in comparators"
                                :label="cp.name"
                                :value="cp.value"
                                :key="cp.value"
                              />
                            </el-select>
                          </el-col>
                          <!-- 属性 -->
                          <el-col :span="5" v-if="cond.identifier == 'report'">
                            <el-input
                              v-model="param.value"
                              auto-complete="off"
                              size="small"
                              @input="setlisteners"
                            />
                          </el-col>
                          <!-- 事件 -->
                          <el-col :span="5" v-else>
                            <div
                              v-for="(item, index) in eventsList"
                              :key="index"
                            >
                              <div
                                v-for="(item2, i) in item.outputData"
                                :key="i"
                              >
                                <div
                                  v-if="
                                    cond.identifier == item.identifier &&
                                    param.identifier == item2.identifier
                                  "
                                >
                                  <el-select
                                    v-model="param.value"
                                    size="small"
                                    @change="setlisteners"
                                    v-if="
                                      item2.dataType.type == 'enum' ||
                                      item2.dataType.type == 'bool'
                                    "
                                  >
                                    <el-option
                                      v-for="cp in item2.dataType.specsArray"
                                      :label="cp.value"
                                      :value="cp.key"
                                      :key="cp.key"
                                    />
                                  </el-select>
                                  <el-input
                                    v-model="param.value"
                                    auto-complete="off"
                                    size="small"
                                    :placeholder="
                                      item2.dataType.specs.min +
                                      '-' +
                                      item2.dataType.specs.max
                                    "
                                    @input="setlisteners"
                                    v-else-if="item2.dataType.type == 'int32'"
                                    :oninput="`if(isNaN(value)) { value = null } {if(value>${item2.dataType.specs.max})value=${item2.dataType.specs.max}} {if(value<${item2.dataType.specs.min})value=${item2.dataType.specs.min}}`"
                                  />

                                  <el-input
                                    v-model="param.value"
                                    auto-complete="off"
                                    size="small"
                                    :placeholder="
                                      item2.dataType.specs.min +
                                      '-' +
                                      item2.dataType.specs.max
                                    "
                                    @input="setlisteners"
                                    v-else-if="item2.dataType.type == 'float'"
                                    :oninput="`if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} {if(value>${item2.dataType.specs.max})value=${item2.dataType.specs.max}} {if(value<${item2.dataType.specs.min})value=${item2.dataType.specs.min}}`"
                                  />

                                  <el-input
                                    v-model="param.value"
                                    auto-complete="off"
                                    size="small"
                                    :maxlength="item2.dataType.specs.length"
                                    @input="setlisteners"
                                    v-else-if="item2.dataType.type == 'text'"
                                  />
                                  <el-input
                                    v-model="param.value"
                                    auto-complete="off"
                                    size="small"
                                    placeholder="毫秒"
                                    @input="setlisteners"
                                    v-else-if="item2.dataType.type == 'date'"
                                  />
                                </div>
                              </div>
                            </div>
                            <!-- <el-input v-model="param.value" auto-complete="off" size="small" @input="setlisteners" /> -->
                          </el-col>
                          <el-col :span="1">
                            <el-button
                              style="margin-left: 6px"
                              type="danger"
                              icon="el-icon-delete"
                              size="mini"
                              circle
                              @click="removeParmeter(paramIndex, cond)"
                            />
                          </el-col>
                        </el-row>
                      </el-col>
                      <el-col
                        :span="2"
                        v-if="
                          !cond?.identifier?.endsWith(':*') && cond.identifier
                        "
                      >
                        <el-button
                          type="primary"
                          size="mini"
                          icon="el-icon-plus"
                          circle
                          @click="addParmeter(cond)"
                        />
                      </el-col>
                    </el-row>
                  </div>
                  <el-button
                    type="danger"
                    size="small"
                    icon="el-icon-delete"
                    style="margin-left: 10px"
                    @click="handleRemoveCondition(item, condIndex)"
                  ></el-button>
                </div>
              </div>
            </div>
            <el-button
              type="primary"
              size="small"
              style="margin-top: 12px"
              @click="handleAddCondition(item)"
              >新增条件</el-button
            >
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <el-button
      style="margin-top: 10px"
      type="primary"
      size="small"
      @click="handleAdd"
      >新增监听器</el-button
    >
  </div>
</template>

<script>
// import { getObjectModel } from '@/views/iot/equipment/api/products.api'
import SelectProduct from "@/components/rule/select-product.vue";
import SelectDevice from "@/components/rule/select-device.vue";
import { reqThingModelByProductKey } from "@api/model";
import { reqByProductKey } from "@/api/rule";

export default {
  components: {
    SelectProduct,
    SelectDevice,
  },
  props: {
    listeners: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      activeName: [], // 初始化为空数组
      list: [
        //   {
        //   type: "device",//类型：设备device
        //   pk: "",//产品id
        //   // config: "",//listeners值转字符串
        //   conditions: [
        //     {
        //       parameters: [],//参数集合
        //       // identifier: "",//标识
        //       // type: "",//标识类型
        //     }
        //   ]
        // }
      ],
      comparators: [
        { name: "大于", value: ">" },
        { name: "等于", value: "==" },
        { name: "小于", value: "<" },
        { name: "不等于", value: "!=" },
        { name: "包含", value: "in" },
        { name: "不包含", value: "notin" },
        { name: "相似", value: "like" },
        { name: "任意", value: "*" },
      ],
      options: [],
      properties: [],
    };
  },
  watch: {
    "list.length": {
      handler() {
        this.setlisteners();
      },
      // deep: true // 开启深度监听
    },
  },
  methods: {
    // 选择产品-调用物模型
    handleSelectProduct(product) {
      console.log(product, "选择产品");
      if (!product.deviceType) return;
      this.list[product.index].pk = product.deviceType; //产品类型
      // this.list[product.index].dn = product.imei;//设备编码
      this.list[product.index].dn = ""; //设备编码
      // console.log(this.list, 'this.list');
      // 1、更换产品时条件清空 注意：编辑时会清空 有bug
      // this.list.forEach(item => {
      //   item.conditions.forEach(item2 => {
      //     item2.parameters = []
      //     delete  item2.identifier
      //     delete  item2.type
      //   })
      // })
      this.onThingModel(product); // 获取物模型
    },
    // 获取物模型
    async onThingModel(product) {
      // let res = await reqThingModelByProductKey({
      //   requestId: product.id,
      //   data: product.id,
      // });
      let res = await reqByProductKey(product.deviceType);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { data } = res.data;
      // console.log(data, 'data');
      this.options = [];
      this.options.push({
        name: "通配",
        items: [
          {
            type: "state",
            identifier: "state:*",
            name: "设备上下线",
          },
          {
            type: "event",
            identifier: "event:*",
            name: "任意事件上报",
          },
          {
            type: "service_reply",
            identifier: "service_reply:*",
            name: "任意服务回复",
          },
        ],
      });
      let items = [];
      this.options.push({
        name: "精确匹配",
        items: items,
      });
      if (!data) {
        this.setlisteners();
        return;
      }
      items.push({
        type: "property",
        identifier: "report",
        name: "属性上报",
      });
      // 事件
      data.model.events.forEach((item) => {
        items.push({
          type: "event",
          identifier: item.identifier,
          name: item.name,
        });
      });
      this.eventsList = data.model.events;
      this.eventsList.forEach((item) => {
        item.outputData.forEach((item2) => {
          if (item2.dataType.type == "enum") {
            item2.dataType.specsArray = Object.keys(item2.dataType.specs).map(
              (key) => {
                return { key: parseInt(key), value: item2.dataType.specs[key] };
              }
            );
          } else if (item2.dataType.type == "bool") {
            item2.dataType.specsArray = Object.keys(item2.dataType.specs).map(
              (key) => {
                return { key: parseInt(key), value: item2.dataType.specs[key] };
              }
            );
          }
        });
      });
      console.log(this.eventsList, "this.eventsList11");

      // 服务
      // data.model.services.forEach(item => {
      //   items.push({
      //     type: 'service',
      //     identifier: item.identifier,
      //     name: item.name,
      //   })
      // })
      this.properties = [];
      // 任意
      // this.properties.push({
      //   identifier: '*',
      //   name: '任意',
      // })
      data.model.properties.forEach((item) => {
        this.properties.push({
          identifier: item.identifier,
          name: item.name,
        });
      });
      this.setlisteners();
    },
    // 选择设备
    handleEmits(product) {
      if (!product.imei) return;
      this.list[product.index].dn = product.imei; //设备名称
      this.setlisteners();
    },
    setlisteners() {
      // this.list = this.list.map((item) => {
      //   // item.config = JSON.stringify(item);
      //   if (item.config) {
      //     item = JSON.parse(item.config || '{}')
      //   }
      //   return item
      // });
      // console.log(this.list,'this.list444');
      this.$emit("onlisteners", this.list);
    },
    // 选中事件条件
    onOutputData(e) {
      console.log(e, "选中事件条件");
      console.log(this.outputData);
    },
    handleAdd() {
      this.list.push({
        type: "device", //类型：设备device
        pk: "", //产品id
        // config: "",//listeners值转字符串
        conditions: [
          {
            parameters: [], //参数集合
            // identifier: "",//标识
            // type: "",//标识类型
          },
        ],
      });
    },
    removeListener(index) {
      this.list.splice(index, 1);
    },
    // 选择条件
    conditionChange(cond, index, e, condIndex) {
      console.log(cond, index, e);
      // 监听器:事件:属性要从事件的输出参数取
      this.eventsList.forEach((item) => {
        if (item.identifier == e) {
          this.outputData = item.outputData;
        }
      });
      // console.log(this.list,'this.list');
      // console.log(this.list[index].conditions[condIndex]);
      this.options.forEach((item) => {
        item.items.forEach((item2) => {
          if (item2.identifier == e) {
            this.list[index].conditions[condIndex].type = item2.type || "";
            return;
          }
        });
      });
      this.setlisteners();
    },
    // 新增条件
    handleAddCondition(item) {
      if (!item.conditions) {
        item.conditions = [];
      }
      item.conditions.push({
        parameters: [],
      });
      this.setlisteners();
    },
    // 删除条件
    handleRemoveCondition(item, index) {
      item.conditions.splice(index, 1);
      this.setlisteners();
    },
    // 新增参数
    addParmeter(cond) {
      // console.log(cond);
      // console.log(this.list);
      if (!cond.parameters) {
        cond.parameters = [];
      }
      cond.parameters.push({});
    },
    // 删除参数
    removeParmeter(index, cond) {
      cond.parameters.splice(index, 1);
      this.setlisteners();
    },
    // 编辑
    getList() {
      this.list = this.listeners.map((item) => {
        if (item.config) {
          // 编辑
          item = JSON.parse(item.config || "{}");
        }
        return item;
      });
      // console.log(this.list, 'list');
    },
    getDestroy() {
      this.list = [];
    },
  },
  created() {
    // 在组件创建后填充数组
    for (let i = 0; i < 100; i++) {
      this.activeName.push(i);
    }
  },
  beforeDestroy() {},
};
</script>

<style lang="less" scoped>
.list-box {
  margin-top: 10px;

  .cu-title {
    width: calc(100% - 30px);
    cursor: auto;
    display: flex;
    align-items: center;

    .item {
      width: 250px;
      margin-right: 10px;
    }
  }
}

.condition-box {
  background-color: @ruleBgcolor;
  padding: 15px;
  border-top: @ruleBgcolor3;

  .main {
    border: @ruleBgcolor2;

    .title {
      padding: 12px;
      color: @ruleColor;
      font-weight: 600;
      border-bottom: @ruleBgcolor3;
    }

    .main-box {
      padding: 10px;

      .box {
        display: flex;
        align-items: center;

        .item {
          border: @ruleBgcolor2;
          padding: 6px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 10px;
          flex: 1;

          .param-item {
            margin-bottom: 8px;
          }
        }
      }
    }
  }
}

.flex {
  display: flex;
}

// 折叠
.el-collapse {
  border-top: none;
  border-bottom: none;
  border-radius: 5px !important;
}

::v-deep .el-collapse-item__header {
  color: #8299c9;
  font-size: 14px;
  background-color: @ruleBgcolor !important;
  border: none;
  border-radius: 5px !important;
  padding: 0 12px;
}

::v-deep .el-collapse-item__content {
  color: #fff;
  font-size: 13px;
  border: none !important;
  //   padding: 10px 0 10px 10px;
  background-color: transparent !important;
  border-radius: 0 0 5px 5px !important;
}

::v-deep .el-collapse-item__wrap {
  border: none;
  background-color: transparent;
}

// 折叠结束

// 设备监听单选按钮
::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #7367f0;
  background: #7367f0;
}

::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #7367f0;
}

::v-deep .el-radio:last-child {
  display: flex;
}
</style>
